﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace swaganomics.Backend
{
    public class ServerConnector
    {
        public static Uri APIRoot = new Uri("http://valhalla.io/PersonalProjects/YRS2012/hub.php"); 

        public static string GetServerResponse(string input)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(APIRoot);
            request.Method = "POST";
            request.ContentType = "application/octet-stream";
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            string returnPackage = responseFromServer;

            reader.Close();
            dataStream.Close();
            response.Close();

            if (returnPackage.Contains("error_has_swag"))
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                DataFormats.ServerResponse.ErrorFormat error = jss.Deserialize<DataFormats.ServerResponse.ErrorFormat>(returnPackage);

                throw new Exception(error.Error_Name + "\n" + error.Error_Desc);
            }

            return returnPackage;
        }
    }
}
